package com.db.priceApp.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

import com.db.priceApp.domain.InstrumentList;
import com.db.priceApp.domain.Price;

public class ReaderFromFile {

	private static final String[] DEFAULT_INSTRUMENTS = {"GA", "GB", "GC"};
	private final InstrumentList instruments;

	public ReaderFromFile(InstrumentList instruments) {
		this.instruments = instruments;
	}

	public void readInstrumentListFromFile(String filename)
			throws IOException {

		Scanner scanner = new Scanner(new FileInputStream(filename));
		while (scanner.hasNext()) {
			parceInstruments(scanner.nextLine());
		}
		scanner.close();
		return;
	}

	private void parceInstruments(String nextLine) throws IOException {

		Scanner scanner = new Scanner(nextLine);
		String instrName;
		int leftBoundary = 0;
		int rightBoundary = 0;

		// read name of the instrument
		if (!scanner.hasNext()) {
			illegalDataFormat(scanner);
		}

		instrName = scanner.next();

		try {
			// read left boundary
			if (!scanner.hasNext()) {
				illegalDataFormat(scanner);
			}
			leftBoundary = Integer.parseInt(scanner.next());

			// read right boundary
			if (!scanner.hasNext()) {
				illegalDataFormat(scanner);
			}
			rightBoundary = Integer.parseInt(scanner.next());
		} catch (NumberFormatException e) {
			illegalDataFormat(scanner);
		}
		
		instruments.addInstrument(instrName, new Price(leftBoundary,
				rightBoundary));
		scanner.close();
	}

	private void illegalDataFormat(Scanner scanner) throws IOException {
		scanner.close();
		System.out.println("wrong data format");
		throw new IOException();
	}

}
